package com.wkg.music_player.controller;

import com.wkg.music_player.mapper.UserMapper;
import com.wkg.music_player.model.User;
import com.wkg.music_player.tools.Constant;
import com.wkg.music_player.tools.ResponseBodyMessage;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.constraints.NotBlank;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.server.ResponseStatusException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

import static com.wkg.music_player.tools.Constant.USERINFO_SESSION_KEY;


@RestController
@Validated
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private BCryptPasswordEncoder bCryptPasswordEncoder;

    @RequestMapping("/login")
    public ResponseBodyMessage<User> login(@NotBlank(message = "用户名不能为空") @RequestParam String username,
                                           @NotBlank(message = "密码不能为空") @RequestParam String password,
                                           HttpServletRequest request) {
        User user = userMapper.selectByName(username);
        if (user == null) {
            System.out.println("登录失败!");
            return new ResponseBodyMessage<>(-1, "登录失败!", user);
        } else {
            boolean flg = bCryptPasswordEncoder.matches(password, user.getPassword());
            if (!flg) {
                return new ResponseBodyMessage<>(-1, "用户名和密码错误!", user);
            }
            request.getSession().setAttribute(USERINFO_SESSION_KEY, user);
            return new ResponseBodyMessage<>(0, "登录成功!", user);
        }
    }

    @RequestMapping("/register")
    public ResponseBodyMessage<Boolean> register(@NotBlank(message = "用户名不能为空") @RequestParam String username,
                                                 @NotBlank(message = "密码不能为空") @RequestParam String password) {
        User user = userMapper.selectByName(username);
        if (user != null) {
            System.out.println("注册用户已存在!");
            return new ResponseBodyMessage<>(-1, "注册用户已存在!", false);
        }

        String newPassword = bCryptPasswordEncoder.encode(password);
        int count = userMapper.insertNewUser(username, newPassword);
        if (count != 1) {
            return new ResponseBodyMessage<>(-1, "注册失败!", false);
        }
        return new ResponseBodyMessage<>(0, "注册成功!", true);
    }
}
